﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OrderingPlatform.Model;
using OrderingPlatform.Infrastructure;
using OrderingPlatform.Model.OrderManage;
using OrderingPlatform.Model.ProductManage;
using OrderingPlatform.MvcExtension;
using OrderingPlatform.MvcPager.Mvc;
using OrderingPlatform.DalService.OrderManage;

namespace OrderingPlatform.BllService.OrderService
{
    public class OrderService
    {
        private readonly OrderDal _orderDal = new OrderDal();
        public CallBackPager<OrderBase> GetList(OrderModel model, int pageIndex, int pageSize)
        {
            try
            {
                var result = new CallBackPager<OrderBase> { Pager = _orderDal.GetList(model, pageIndex, pageSize) };
                return result;
            }
            catch (Exception)
            {
                var result = new CallBackPager<OrderBase> { Pager = new PagedList<OrderBase>(new List<OrderBase>(), pageIndex, pageSize, 0) };
                return result;
            }
        }

        public List<OrderDetailModel> GetOrderDetail(Guid orderId)
        {
            try
            {
                return _orderDal.GetOrderDetail(orderId);
            }
            catch (Exception)
            {
                return new List<OrderDetailModel>();
            }
        }

       

       
        /// <summary>
        /// 更新COOKIES购买数量
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="buyCount"></param>
        public void ShoppingCartUpdate(Guid? productId, int buyCount)
        {
            var cookies = CookiesManage.GetCookie(ConstLibrary.ShoppingCartCookies);
            if (string.IsNullOrEmpty(cookies)) return;
            var list = cookies.JsonToObject<List<ProductTopModel>>();
            if (buyCount == 0)
            {
                list = list.Where(a => a.ProductId != productId).ToList();
            }
            else
            {
                var model = list.FirstOrDefault(a => a.ProductId == productId);
                if (model == null) return;
                model.BuyCount = buyCount;
            }
            CookiesManage.SetCookie(ConstLibrary.ShoppingCartCookies, list.ToJson(), 30);
        }
        /// <summary>
        /// 获取COOKIES
        /// </summary>
        /// <returns></returns>
        public List<ProductTopModel> ShoppingCart()
        {
            var cookies = CookiesManage.GetCookie(ConstLibrary.ShoppingCartCookies);
            if (string.IsNullOrEmpty(cookies)) return new  List<ProductTopModel>() ;
            var list = cookies.JsonToObject<List<ProductTopModel>>();
            return list;
        }
    }
}
